import { defineStore } from 'pinia';
import {listCollection} from "@api/collection";

export const useSystemStore = defineStore('system', {
    state: () => ({
        namespace: localStorage.getItem('namespace') ?? "namespace_1",
        collection: localStorage.getItem("collection"),
        collections: localStorage.getItem("collections") ? JSON.parse(localStorage.getItem("collections")) : [],
    }),
    getters: {
        collectionData (state) {
            if (state.collections?.length) {
                return state.collections.find((col) => col.collectionName === state.collection)
            }
            return null;
        }
    },
    actions: {
        updateCollection () {
            listCollection().then((res) => {
                this.setCollections(res.data.data);
            });
        },
        setNamespace(namespace) {
            this.namespace = namespace;
            localStorage.setItem("namespace", namespace);
            this.updateCollection();
        },
        setCollection(collection) {
            this.collection = collection;
            localStorage.setItem("collection", collection);
        },
        setCollections(collections) {
            this.collections = collections;
            localStorage.setItem("collections", JSON.stringify(collections));
        }
    }
});
